// http://api.jquery.com/jQuery.ajax/

// general options for all ajax request
$.ajaxSetup({
	type: "GET",
	statusCode: {
		404: function() {
			alert("page not found");
		},
		500: function() { 
			alert("Server error");
		}
	}
});

var myZona = new Array();
var marker = new Array();
var contentString = new Array();
var infowindow = new Array();
var pos;
$(document).ready(function() {  
if(navigator.geolocation) {
	navigator.geolocation.getCurrentPosition(function(position) {
	pos = new google.maps.LatLng(position.coords.latitude,
                                             position.coords.longitude);
	pintaMapa("map_canvas");

	});
}
else
{

}
});

/**
* 
* 
**/
function pintaMapa(destID) {
	
	if ( $('#' + destID).length = 0 ) { return;}
	$.ajax({
		dataType: 'text html',
		url: '/biotika/ObtenerPuntos?tipo=farmacia&latitud='+pos.Ya+'&longitud='+pos.Za
	})
	.done(function(data){
		xmlDoc = $.parseXML( data );
		$xml = $( xmlDoc );
		$puntos = $xml.find( "punto" );
		if  ( $puntos.length > 0 ) {
			var ptoCentro = pos; // Madrid, aprox!!!
			var myOptions = {
				zoom: 12,
				center: ptoCentro,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			}
			var map = new google.maps.Map(document.getElementById(destID), myOptions);
			var i = 0;
			$.each ( $puntos, function() {
			//$.each ( $puntos, function(key, val) {
				var titulo = $(this).find("titulo").text();
				var url = $(this).find("url").text();
				myZona[i] = new google.maps.LatLng($(this).find("latitud").text(), $(this).find("longitud").text()); 
				contentString[i] = '<div class="google-content">'+
					'<h2>' + titulo + '</h2>'+
					'<div class="bodyContent">'+
					'<p>' +  $(this).find("desc").text() + '</p>'+
					'<p>URL: <a href="'+url+'">' +  url + '</a></p>'+
					'</div>'+
					'</div>';
				infowindow[i] = new google.maps.InfoWindow({ content: contentString[i] });
				
				marker[i] = new google.maps.Marker({ position: myZona[i], map: map, title: titulo });
				
				if(i == 0)
					marker[i].setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png');
					
				eval ( "google.maps.event.addListener( marker[" + i + "], 'click', function() { infowindow["+i+"].open( map, marker["+i+"] ); })");
				i++;
			});
		}
	});
}
